package com.hymjweb.demo.hymj.system_maintenance.user.service;

import com.github.pagehelper.PageInfo;
import com.hymjweb.demo.framework.cache.service.GlobalCacheService;
import com.hymjweb.demo.framework.result.MIniUIGridResultMap;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.framework.util.ShiroUtil;
import com.hymjweb.demo.hymj.department_manage.bean.XtDepartmentPojo;
import com.hymjweb.demo.hymj.department_manage.service.XtDepartmentService;
import com.hymjweb.demo.hymj.native_bill_manage.bean.BNativeBillPojo;
import com.hymjweb.demo.hymj.native_bill_manage.service.BNativeBillService;
import com.hymjweb.demo.hymj.system_maintenance.user.bean.XtUserCachePojo;
import com.hymjweb.demo.hymj.system_maintenance.user.bean.XtUserPojo;
import com.hymjweb.demo.hymj.system_maintenance.user.mapper.XtUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class XtUserService extends BaseService {

    @Autowired
    private XtUserMapper xtUserMapper;

    @Autowired
    private XtDepartmentService xtDepartmentService;

    @Autowired
    private BNativeBillService bNativeBillService;

    @Autowired
    private GlobalCacheService globalCacheService;


    public List<XtUserCachePojo> findCacheAll(Map map){
        List<XtUserCachePojo> pojos= xtUserMapper.findCacheAll(map);
        return pojos;
    }

    public List<XtUserPojo> getXtUserPojoListNoPage(Map map){
        return xtUserMapper.findAll(map);
    }

    public Object getPageList(Map map) {
        // 分页初始化
        this.pageListInit(map);
        List list = getXtUserPojoListNoPage(map);
        PageInfo pageInfo = new PageInfo(list);
        MIniUIGridResultMap resultMap = new MIniUIGridResultMap(pageInfo);
        return resultMap;
    }

    public XtUserPojo findObjectById(String id){
        return xtUserMapper.findObjectById(id);
    }

    public List<XtUserPojo> findByDepartmentId(String departmentId){
        return xtUserMapper.findByDepartmentId(departmentId);
    }

    public XtUserPojo findUK(String mobile){
        return xtUserMapper.findUK(mobile);
    }

    public List<XtUserPojo> queryCustomerSalesmanByKey(String key) {
        return xtUserMapper.queryCustomerSalesmanByKey(key);
    }

    public XtUserPojo queryLoginUserPojo() {
        return this.getSystemUserPojo();
    }

    @Transactional(rollbackFor = {Exception.class})
    public int insert(XtUserPojo pojo) throws Exception{

        if(pojo == null){
            throwException("添加用户参数错误!");
        }

        // 号码是 UK,检测是否有重复用户存在
        XtUserPojo xtUserPojo = findUK(pojo.getMobile());

        if(xtUserPojo != null){
            throwException("添加的用户电话号码已经被【" + xtUserPojo.getName() + "】占用");
        }



        // 设置id
        pojo.setId(this.getSysStrId());
        // 生成密码盐值
        String generateSalt = ShiroUtil.generateSalt();
        // 加密后的密码
        String generatePwdEncrypt = ShiroUtil.generatePwdEncrypt(pojo.getPassword(),generateSalt);

        pojo.setSalt(generateSalt);
        pojo.setPassword(generatePwdEncrypt);

        String czyId = this.getLoginCzyId();
        Date date = this.getSysTime();

        pojo.setCreateTime(date);
        pojo.setCreateUserId(czyId);
        pojo.setUpdateTime(date);
        pojo.setUpdateUserId(czyId);

        int affectRows = xtUserMapper.insert(pojo);
        if(affectRows > SysConstant.INT_ZERO){
            // 重新加载字典表缓存
            globalCacheService.loadXtUserCache();
        }
        return affectRows;
    }

    @Transactional(rollbackFor = {Exception.class})
    public int update(XtUserPojo pojo) throws Exception{
        if(pojo == null){
            throwException("更新用户参数错误!");
        }

        XtUserPojo xtUserPojo = findUK(pojo.getMobile());
        if(xtUserPojo==null){
            throwException("待更新用户对象为空，更新失败!");
        }

        String password = pojo.getPassword();

        if(DataTypeUtil.isEmptyStr(password)){
            pojo.setSalt(xtUserPojo.getSalt());
            pojo.setPassword(xtUserPojo.getPassword());
        }
        else{
            // 生成密码盐值
            String generateSalt = ShiroUtil.generateSalt();
            // 加密后的密码
            String generatePwdEncrypt = ShiroUtil.generatePwdEncrypt(pojo.getPassword(),generateSalt);

            pojo.setSalt(generateSalt);
            pojo.setPassword(generatePwdEncrypt);
        }

        pojo.setUpdateUserId(this.getLoginCzyId());
        pojo.setUpdateTime(this.getSysTime());

        int affectRows = xtUserMapper.update(pojo);
        if(affectRows > SysConstant.INT_ZERO){
            // 更新 session 中的当前用户关于个人对象及部门对象信息
            if(pojo.getId().equals(this.getLoginCzyId())){
                updateSessionLoginUserPojo(pojo);
            }
            // 重新加载字典表缓存
            globalCacheService.loadXtUserCache();
        }
        return affectRows;
    }

    @Transactional(rollbackFor = {Exception.class})
    public int delete(String id) throws Exception{
        if(DataTypeUtil.isEmptyStr(id)){
           throwException("删除用户参数错误!");
        }

        //删除员工时，如果该员工是某部门的领导，请更改领导信息后再进行删除。
        List<XtDepartmentPojo> xtDepartmentPojoList = xtDepartmentService.findByLeaderId(id);

        if(xtDepartmentPojoList != null && !xtDepartmentPojoList.isEmpty() ){
            throwException("删除的用户是部门领导，不能删除!");
        }

        Map<String,Object> param = new HashMap<>();
        param.put("createOrUpdateUserId",id);
        List<BNativeBillPojo> bNativeBillPojoList = bNativeBillService.getNoPageList(param);

        if(bNativeBillPojoList!=null || !bNativeBillPojoList.isEmpty()){
            throwException("删除的用户在分单中有创建分单对象，不能删除!");
        }

        int affectRows = xtUserMapper.delete(id);
        if(affectRows > SysConstant.INT_ZERO){
            // 重新加载字典表缓存
            globalCacheService.loadXtUserCache();
        }
        return  affectRows;
    }

    @Transactional(rollbackFor = {Exception.class})
    public int resetPassword(String pwd1){
        String generateSalt = ShiroUtil.generateSalt();
        String generatePwdEncrypt = ShiroUtil.generatePwdEncrypt(pwd1,generateSalt);
        String czyId = this.getLoginCzyId();
        Date updateTime = this.getSysTime();
        int affectRows = xtUserMapper.resetPassword(czyId,generatePwdEncrypt,generateSalt,updateTime,czyId);
        return affectRows;
    }

    public XtUserPojo getUserPojoByMoible(String mobile) {
        if(DataTypeUtil.isEmptyStr(mobile)){
            return null;
        }
        return xtUserMapper.getUserPojoByMobile(mobile);
    }
}
